﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTracker.Models;
using ScrumTracker.Helpers;

namespace ScrumTracker.Controllers
{
    public class AttachmentsController : Controller
    {
        //
        // GET: /Attachments/

        public ActionResult Create(int IssueId)
        {
            var ctx = ScrumTrackerEntities.Instance;
            foreach (string fileKey in Request.Files)
            {
                var file = Request.Files[fileKey];
                string relativePath = string.Format("~/content/uploads/issues/{0}/{1}", IssueId, file.FileName);
                string filePath = Server.MapPath(relativePath);
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
                file.SaveAs(filePath);
                var issue = ctx.Issues.Include("Attachments").SingleOrDefault(i => i.IssueId == IssueId);
                if (issue.Attachments.Any(a => a.RelativePath == relativePath) == false)
                {
                    var attachment = new Attachment() { ContentType = file.ContentType, CreatedAt = DateTime.UtcNow, CreatedBy = SessionHelper.CurrentUser.UserId, RelativePath = relativePath };
                    issue.Attachments.Add(attachment);
                }
            }
            ctx.SaveChanges();
            return Json(new { success = true });
        }
    }
}
